<?php

class ctrl_ali_aliProduct extends L {

    /**
     * 描述 ：产品管理页面展示
     * 作者 ：Zoro.Zhu
    **/
    public function index(){
        $this->view->aliProductState = model_com::getVsConfig('aliProductState');
        $this->view->pubilcAccount = model_vsAccount::getAccountList('pdd');
        $this->view->_pagingHtml = $this->paging();
        $this->view->headTitle = '产品管理';
        $this->view->createDateStart = date('Y-m-d') . ' 00:00:00';
        $this->display('/html/ali/aliProduct.html');
    }

    /**
     * 描述 : 获取分页
     * 作者 : Zoro.Zhu
     */
    public function &paging($params = array()){
        $sql = model_aliProduct::searchSql($params);
        $config = array(
            "<input type=\"checkbox\" name=\"checkAll\">" => '<input type="checkbox" name="check[]" class="checkbox"  value="{`productId`}">',
            '阿里的商品ID<br>类目' => "<a target=\"_blank\" href='https://detail.1688.com/offer/{`productId`}.html'>{`productId`}</a><br>{`categoryName`}",
            '供应商账号<br>标题<br>拼多多的商品ID' => '<a target="_blank" href=\'https://{`manuName`}.1688.com/page/merchants.htm\'>{`manuName`}</a><br>{`proName`}<br>{`pddId`}',
            'SKU列表' => '<div style="text-align: left">{`_skuList`}</div>',
            '刊登账号<br>刊登状态' => '{`account`}<br>{`_state`}',
            '错误信息<br>报错时间' => '{`errorInfo`}<br>{`errorDate`}',
            '视频' => '{`_mainVedio`}',
            '图片' => '{`_image`}',
            '创建时间' => array(
                '_attr' => array(
                    'body' => '{`createDate`}',
                    'sort' => 'createDate'
                )
            ),
            '_attr' => array(
                "attr" => array (
                    "table" => 'id=aliProductList class="table table-hover table-condensed table-striped table-scroll jsHoverDetails textC"',
                    "btr" => "align='center' class='of-paging_item_odd tr_{`productId`}'",
                ),
                'data' => &$sql,
                'params' => &$params,
                'call' => array($this, 'asCall'),
                'method' => __METHOD__,
                'save' => 'auto',
                'empty' => '查无此数据'
            )
        );
        return $this->_com->paging($config);
    }

    /**
     * 描述 : 整理数据
     * 作者 : Zoro.Zhu
     */
    public function asCall(&$data){
        $stateInfo = model_com::getVsConfig('aliProductState');
        foreach($data['data'] as &$val){
            //错误信息
            $error = json_decode($val['errorData'], true);
            !empty($error['info']) && $val['errorInfo'] = $error['info'];
            !empty($error['date']) && $val['errorDate'] = $error['date'];
            //状态
            $val['_state'] = $stateInfo[$val['state']];

            $aliData = json_decode($val['data'], true);
//            $val['_image'] = "<a class='showImg'><img style='width: 60px;height: 60px' src='https://cbu01.alicdn.com/" .
//                join("'></a><a class='showImg'><img style='width: 60px;height: 60px' src='https://cbu01.alicdn.com/", $aliData['productInfo']['image']['images']) . "'></a>";
            $val['_image'] = "";
            foreach($aliData['productInfo']['image']['images'] as $img){
                $val['_image'] .= "<a href='https://cbu01.alicdn.com/{$img}' data-lightbox='{$val['productId']}' data-title='{$val['productId']}'><img style='width: 45px;height: 45px' src='https://cbu01.alicdn.com/{$img}'></a>";
            }
            $val['proName'] = $aliData['productInfo']['subject'];
            !empty($aliData['productInfo']['categoryName']) && $val['categoryName'] = $aliData['productInfo']['categoryName'];
            $price = 0;
            foreach ($aliData['productInfo']['saleInfo']['priceRanges'] as $row){
                if($row['price'] > $price){
                    $price = $row['price'];
                }
            }
            $skuName = "<table><tr class='tr_center'><td>属性</td>";
            $skuImg = "</tr><tr class='tr_center'><td>图片</td>";
            $sku = "</tr><tr class='tr_center'><td>SKU</td>";
            $skuPrice = "</tr><tr class='tr_center'><td>采购价￥</td>";
            $skuShopPrice = "</tr><tr class='tr_center'><td>售价￥</td>";
            $stock = "</tr><tr class='tr_center'><td>库存</td>";
            foreach ($aliData['productInfo']['skuInfos'] as $key => $row){
                if($key > 7){
                    $skuName .= "<td>...</td>";
                    $skuImg .= "<td>...</td>";
                    $sku .= "<td>...</td>";
                    $skuPrice .= "<td>...</td>";
                    $skuShopPrice .= "<td>...</td>";
                    $stock .= "<td>...</td>";
                    break;
                }
                $pricePurchase = !empty($row['price']) ? $row['price'] : $price;
                //拼凑sku列表数据
                $name = "";
                foreach($row['attributes'] as $attr){
                    $name .= $attr['attributeValue'] . ' ';
                }
                $skuName .= "<td>{$name}</td>";

                if(!empty($row['attributes'][0]['skuImageUrl'])){
                    $skuImg .= "<td><a href='https://cbu01.alicdn.com/{$row['attributes'][0]['skuImageUrl']}' data-lightbox='{$row['skuId']}' data-title='{$row['skuId']}'><img style='width: 45px;height: 45px' src='https://cbu01.alicdn.com/{$row['attributes'][0]['skuImageUrl']}'></a></td>";
//                    $skuImg .= "<td><a class='showImg'><img style='width: 45px;height: 45px' src='https://cbu01.alicdn.com/{$row['attributes'][0]['skuImageUrl']}'></a></td>";
                }else{
                    $skuImg .= "<td></td>";
                }

                $sku .= "<td>{$row['skuId']}</td>";
                $skuPrice .= "<td>" . $pricePurchase ."</td>";
                $skuShopPrice .= "<td>" . ctrl_pdd_mq::shopPrice($pricePurchase) . "</td>";
                $stock .= "<td>{$row['amountOnSale']}</td>";
            }
            $val['_skuList'] = $skuName . $skuImg . $sku . $skuPrice . $skuShopPrice . $stock . "</tr></table>";
            !empty($aliData['productInfo']['mainVedio']) && $val['_mainVedio'] = "<a target=\"_blank\" href='{$aliData['productInfo']['mainVedio']}'>视频</a>";
        }
    }

    /**
     * 描述 : 新增和修改的页面展示
     * 作者 : Zoro.Zhu
     */
    public function aliProductUpInfo(){
        if(!empty($_REQUEST['productId'])) {
            $aliProduct = model_aliProduct::getKeyInfo($_REQUEST['productId']);
            if(!empty($aliProduct)){ 
                $this->view->productId = $aliProduct[0]['productId'];
                $this->view->createDate = $aliProduct[0]['createDate'];
                $this->view->data = $aliProduct[0]['data'];
                $this->view->pddId = $aliProduct[0]['pddId'];
            }
        }
        $this->display('/html/ali/aliProductUpInfo.html');
    }

    /**
     * 描述 ：新增或修改数据
     * 作者 ：Zoro.Zhu
    **/
    public function aliProductUpd(){
        //主键为空是新增，否则就是修改
        if(empty($_POST['productId'])){
            $result = model_aliProduct::insertSql($_POST);
        }else{
            $result = model_aliProduct::updateSql($_POST);
        }
        if($result > 0){
            return array('state' => 200, 'info' => '操作成功');
        }else{
            return array('state' => 301, 'info' => '操作无效');
        }
    }

    /**
     * 描述 ：按条件导出数据
     * 作者 ：Zoro.Zhu
    **/
    public function exportCsv(){
        $sql = model_aliProduct::searchSql(array('search' => $_GET));
        $data = L::sql($sql);
        of_base_com_csv::download('导出数据' . time());                     //导出数据的文件名
        of_base_com_csv::download(array('阿里的商品ID','创建时间','拼多多的商品ID','供应商账号',));
        foreach ($data as $row){
            of_base_com_csv::download(array($row['productId'],$row['createDate'],$row['pddId'],$row['manuName'],));
        }
    }

    /**
     * 描述 ：重新执行刊登操作
     * 作者 ：Zoro.Zhu
    **/
    public function againPublic(){
        if(empty($_POST['productStr'])){
            return array('state' => 300, 'info' => '参数异常');
        }
        $productId = explode(',', $_POST['productStr']);
        $productInfo = model_aliProduct::getKeyInfo($productId);
        $error = '';
        foreach ($productInfo as $row){
            if($row['state'] == 45){
                $sql = "UPDATE `ali_product` 
                SET 
                    `state` = 40 
                WHERE
                    `productId` = '{$row['productId']}'";
                L::sql($sql);
                of_base_com_mq::set(['pddProductAdd', $row['productId']], ['productId' => $row['productId'], 'account' => $row['account']]);
            }else if($row['state'] == 35){
                $sql = "UPDATE `ali_product` 
                SET 
                    `state` = 30 
                WHERE
                    `productId` = '{$row['productId']}'";
                L::sql($sql);
                //设置上传图片到pdd的消息队列，上传图片后再进行刊登到pdd
                of_base_com_mq::set(array('pddImgUpload', $row['productId']), array('productId' => $row['productId'], 'account' => $row['account']));
            }else{
                $error .= $row['productId'] . '状态不是刊登错误<br>';
            }
        }
        if($error){
            return array('state' => 303, 'info' => $error . '其它产品操作成功！');
        }else{
            return array('state' => 200, 'info' => '操作成功');
        }
    }

    /**
     * 描述 : 下架产品
     * 作者 : Zoro.Zhu
     */
    public function soldOut(){
        if(empty($_POST['productStr'])){
            return array('state' => 300, 'info' => '参数异常');
        }
        set_time_limit(0);
        $productId = explode(',', $_POST['productStr']);
        $productInfo = model_aliProduct::getKeyInfo($productId);
        $error = '';
        foreach ($productInfo as $row){
            if($row['state'] != 50){
                $error .= $row['productId'] . '状态不是已刊登<br>';
                continue;
            }
            $updStatusRes = serv_rapi_pdd::updProductStatus($row['pddId'], $row['account'], 0);
            if(!empty($updStatusRes['goods_sale_status_set_response']['is_success'])){
                $errorInfo = [
                    'info' => '手动下架',
                    'date' => date('Y-m-d H:i:s')
                ];
                $sql = "UPDATE `ali_product` 
                    SET 
                        `errorData` = '" . addslashes(json_encode($errorInfo)) . "',
                        `state` = 60 
                    WHERE
                        `productId` = '{$row['productId']}'";
                L::sql($sql);
            }else{
                $error .= $row['productId'] . '下架失败<br>';
            }
        }
        if($error){
            return array('state' => 303, 'info' => $error . '其它产品操作成功！');
        }else{
            return array('state' => 200, 'info' => '操作成功');
        }
    }

    /**
     * 描述 : 下架产品
     * 作者 : Zoro.Zhu
     */
    public function delProduct(){
        if(empty($_POST['productStr'])){
            return array('state' => 300, 'info' => '参数异常');
        }
        set_time_limit(0);
        $productId = explode(',', $_POST['productStr']);
        $productInfo = model_aliProduct::getKeyInfo($productId);
        $error = '';
        foreach ($productInfo as $row){
            if($row['state'] != 60){
                $error .= $row['productId'] . '状态不是已下架<br>';
                continue;
            }
            $delProdcuctRes = serv_rapi_pdd::delProduct($row['pddId'], $row['account']);
            if(!empty($delProdcuctRes)){
                $errorInfo = [
                    'info' => '手动删除',
                    'date' => date('Y-m-d H:i:s')
                ];
                $sql = "UPDATE `ali_product` 
                    SET 
                        `errorData` = '" . addslashes(json_encode($errorInfo)) . "',
                        `state` = 70 
                    WHERE
                        `productId` = '{$row['productId']}'";
                L::sql($sql);
            }else{
                $error .= $row['productId'] . '删除失败<br>';
            }
        }
        if($error){
            return array('state' => 303, 'info' => $error . '其它产品操作成功！');
        }else{
            return array('state' => 200, 'info' => '操作成功');
        }
    }

}
return true;